import Vue from 'vue'
import App from './App'
import store from './store'

Vue.prototype.$store = store

Vue.config.productionTip = false

// let env = 'home';
// let env = 'company';
let env = 'alpha';
// let env = 'test'

const USER_KEY = '_USER_INFO_'
function setUser(user) {
	let res = uni.setStorageSync(USER_KEY, user);
	return res;
}
function getUser() {
	let userInfo = uni.getStorageSync(USER_KEY);
	return userInfo;
}
function removeUser() {
	uni.removeStorageSync(USER_KEY);
}
function getUrl(uri) {
  let url = '';
  switch (env) {
    case 'home':
      url = 'http://local.huanbao.io/api/' + uri;
      break;
    case 'alpha':
      url = 'https://huanbao.xiaomlove.com/api/' + uri;
      break;
    case 'company':
      url = 'http://huanbao.local:8080/api/' + uri; 
      break;
	case 'test':
	  url = 'https://test.huanbao.io/api/' + uri; 
	  break;
    default: 
      throw new Error("invalid env: " + env);
      break;
  }
  return url; 
}
Vue.prototype.$getUser = getUser;
Vue.prototype.$setUser = setUser;
Vue.prototype.$getUrl = getUrl;
Vue.prototype.$removeUser = removeUser;

let XSystemInfo = '';
let systemInfo = uni.getSystemInfoSync();
for (var i in systemInfo) {
	let info = systemInfo[i]
	XSystemInfo += i + "=" + info + "&"
}
XSystemInfo = XSystemInfo.substr(0, XSystemInfo.length - 1)

function request (method, uri, params = '', withToken = true, showLoading = true) {
	let __params = Object.assign({}, params);
	if (__params.__resource_id) {
		uri += '/' + __params.__resource_id;
		delete __params.__resource_id;
	}
	delete __params.has_more;
	let url = getUrl(uri);
	
	let XFormIdStr = ''
	let formId = store.getters.getFormId;
	if (formId && formId.length) {
		XFormIdStr = formId.join(',')
		store.commit('setFormId', [])
	}
	let header = {
		"Content-Type": "application/json",
		"Accept": "application/json",
		"X-System-Info": JSON.stringify(systemInfo),
		"X-Form-Id": XFormIdStr
	}
	if (withToken) {
		let userInfo = getUser();
		if (userInfo && userInfo.auth) {
			header.Authorization = "Bearer " + userInfo.auth.access_token
		}
	}
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				title: "加载中..."
			})
		}
		let ID = (new Date()).getTime();
		console.log(`${ID} start: ${method} => ${url} => ` + JSON.stringify(__params))
		uni.request({
			url: url,
			method: method.toUpperCase(),
			header: header,
			data: __params,
			success: (response) => {
				console.log(`${ID} success: `, response)
				if (showLoading) {
					uni.hideLoading()
				}
				if (response.data.ret == -1001) {
					let nowInLoginPage = store.getters.getNowInLoginPage
					console.log(`now in login page`, nowInLoginPage)
					if (nowInLoginPage) {
						return
					}
					store.commit('setNowInLoginPage', true)
					console.log(`navigate to login page`)
					//第三方第一次登录，需要绑定已有账号或进行注册
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return;
				}
				let statusCode = response.statusCode
				if (statusCode == 401) {
					let nowInLoginPage = store.getters.getNowInLoginPage
					console.log(`now in login page`, nowInLoginPage)
					if (nowInLoginPage) {
						return
					}
					store.commit('setNowInLoginPage', true)
					console.log(`navigate to login page`)
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return;
				} else {
					if (response.data.ret != 0) {
						uni.showToast({
							title: response.data.msg,
							icon: "none"
						})
					}
					resolve(response.data);
				}
			},
			fail: (error) => {
				console.log(`${ID} fail: `, error)
				if (showLoading) {
					uni.hideLoading()
				}
				uni.showToast({
					title: error.errMsg,
					icon: "none"
				})
				reject(error)
			},
			complete: (response) => {
				console.log(`${ID} complete: `)
				
			}
		})
		
		
	})
}

Vue.prototype.$request = request;

Vue.prototype.$api = {
	uploadToken: (params = '') => {
		return request('get', 'upload/token', params)
	},
	uploadTokenCloudinary: (params = '') => {
		return request('get', 'upload/token/cloudinary', params)
	},
	registerByWeixinMiniProgram: (params = '') => {
		return request('post', 'register/mini-program', params)
	},
	registerByAccountPassword: (params = '') => {
		return request('post', 'register/account-password', params)
	},
	loginByAccountPassword: (params = '') => {
		return request('post', 'login/account-password', params)
	},
	logout: (params = '') => {
		return request('post', 'logout', params)
	},
	listTopic: (params = '') => {
		return request('get', 'topic', params)
	},
	createTopic: (params = '') => {
		return request('post', 'topic', params)
	},
	showTopic: (params = '') => {
		return request('get', 'topic', params)
	},
	listComment: (params = '') => {
		return request('get', 'comment', params)
	},
	listMyComment: (params = '') => {
		return request('get', 'comment-my', params)
	},
	createComment: (params = '') => {
		return request('post', 'comment', params)
	},
	createLike: (params = '') => {
		return request('post', 'like', params)
	},
	listForumTaxonomy: (params = '') => {
		return request('get', 'forumtaxonomy', params)
	},
	my: (params = '') => {
		return request('get', 'user', params)
	},
	updateUser: (params = '') => {
		return request('put', 'user', params)
	},
	listNotification: (params = '') => {
		return request('get', 'notification', params)
	},
	readNotification: (params = '') => {
		return request('put', 'notification/read', params, true, false)
	},
	deleteNotification: (params = '') => {
		return request('delete', 'notification', params)
	},
	listMyScore: (params = '') => {
		return request('get', 'scores', params)
	},
	getTopicConfig: (params = '') => {
		return request('get', 'topic-config', params)
	},
	search: (params = '') => {
		return request('get', 'search', params)
	},
	listSwiper: (params = '') => {
		return request('get', 'swiper', params)
	},
	listStickyTopic: (params = '') => {
		return request('get', 'topic-sticky', params)
	},
	listMyTopic: (params = '') => {
		return request('get', 'topic-my', params)
	},
	listProvinceCityDistrict: (params = '') => {
		return request('get', 'area/province-city-district', params)
	},
	listProvince: (params = '') => {
		return request('get', 'area/province', params)
	},
	listCity: (params = '') => {
		return request('get', 'area/city', params)
	},
	listDistrict: (params = '') => {
		return request('get', 'area/district', params)
	},
	listArea: (params = '') => {
		return request('get', 'area/list-by-pid', params)
	},
	purchaseConfirm: (params = '') => {
		return request('post', 'order-checkout', params)
	},
	createTopicOrderAndPay: (params = '') => {
		return request('post', 'order', params)
	},
}


App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()
